﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebExpense;
using System.Web.Security;
using Microsoft.Interop.Security.AzRoles;
using System.Drawing;

public partial class Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {       
    }
    protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
    {

        var domainProvider = Membership.Providers["AspNetActiveDirectoryMembershipProvider"];
        if (domainProvider != null)
            if (domainProvider.ValidateUser(txtUsername.Text , txtPassword.Text ))
            {
                if (Request.QueryString["ReturnUrl"] != null)
                {
                    FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, false);
                    ExpenseCommon.Initialize();
                    InitialiseItems();
                }
                else
                {
                    FormsAuthentication.SetAuthCookie(txtUsername.Text, false);
                    ExpenseCommon.Initialize();
                    InitialiseItems();
                    Response.Redirect("~/Index.aspx");
                }
            }
    }


    private void InitialiseItems()
    {
        var userName = txtUsername.Text ; 
        Session["CLIENT_SAM_NAME"] = userName;             
        
        IAzClientContext AzManClientContext;
        var app = (IAzApplication)Application["AZMAN_APP"];
        AzManClientContext = app.InitializeClientContextFromName(userName, "testing", null);
        Session["AZMAN_CLIENT"] = AzManClientContext;
    }

    protected void Login_Click(object sender, EventArgs e)
    {
        var domainProvider = Membership.Providers["AspNetActiveDirectoryMembershipProvider"];
        if (domainProvider != null)
        {
            if (domainProvider.ValidateUser(txtUsername.Text, txtPassword.Text))
            {
                if (Request.QueryString["ReturnUrl"] != null)
                {
                    FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, false);
                    ExpenseCommon.Initialize();
                    InitialiseItems();
                }
                else
                {
                    FormsAuthentication.SetAuthCookie(txtUsername.Text, false);
                    ExpenseCommon.Initialize();
                    InitialiseItems();
                    Response.Redirect("~/Index.aspx");
                }
            }
            else
            {
                errorLabel.ForeColor = Color.Red;
                errorLabel.Text = "Invalid Username or Password";
            }
        }
    }
}
